package com.XDApp.xdbase.activitys;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.BaseApplication;
import com.XDApp.xdbase.adapter.PhotosAdapter;
import com.XDApp.xdbase.bean.BargainPriceTicketInfo;
import com.XDApp.xdbase.bean.TalkInfo;
import com.XDApp.xdbase.bean.TicketInfo;
import com.XDApp.xdbase.bean.TicketPriceInfo;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.HttpProtocol;
import com.XDApp.xdbase.utils.HttpProtocol.PRODUCT_TYPE;
import com.XDApp.xdbase.utils.IRequest;
import com.XDApp.xdbase.utils.MyBaseAdapter;
import com.XDApp.xdbase.utils.SharePopupWindow;
import com.XDApp.xdbase.utils.TicketHttpProtocol;
import com.XDApp.xdbase.utils.XinDaoBaseAdapter;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.view.MyViewPager;
import com.XDApp.xdbase.xinsilu.R;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;

public class TicketDetailActivity extends BaseActivity {
	final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share",
			RequestType.SOCIAL);
	public static final String PARAM_PRODUCTID = "ticket_id";
	public static final String PARAM_PRODUCTNAME = "ticket_name";
	private final int PARAM_TIMER = 0;
	private final int TIMER_DELAY = 5000;
	private final int PAGESIZE = 10;

	/** 商品的ID */
	private String mProductId;
	/** 商品的名字 */
	private String mProductName;

	private ListView mPullToRefreshListView;
	private View topTitle;
	/** 轮播图布局 */
	private View firstView;
	/** 切换tab布局 */
	private View secondView;
	/** 详情布局 */
	private View mIntroView;
	/** 价格布局 */
	private View mPriceView;
	private TextView mTitle;
	/** 收藏按钮 */
	private ImageView mCollect;
	private MyViewPager viewPager;
	/** 进度条布局 */
	private View[] mPlanViews = new View[3];
	/** 置顶的进度条布局，与正常的进度条布局要保持一致 */
	private final TextView[] mTopTabsViews = new TextView[3];
	private final TextView[] mTabsViews = new TextView[3];

	private CommentAdapter mCommentAdapter;
	private PriceAdapter mPriceAdapter;
	private IntroAdapter mIntroAdapter;

	private final List<String> prices = new ArrayList<String>();
	private String mShareContent = "";

	private int mPhotosSize;
	private boolean showMore = false;

	private SharePopupWindow sharePopupWindow = null;

	private final Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case PARAM_TIMER:
				viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
				sendEmptyMessageDelayed(PARAM_TIMER, TIMER_DELAY);
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void initViews() {
		setContentView(R.layout.activity_senery_detail);

		mProductId = getIntent().getStringExtra(PARAM_PRODUCTID);
		mProductName = getIntent().getStringExtra(PARAM_PRODUCTNAME);
		// mProductId=75+"";

		// if (TextUtils.isEmpty(mProductId)) {
		// throw new RuntimeException("productid can't be empty!");
		// }

		mPullToRefreshListView = (ListView) findViewById(R.id.pull_to_listview);

		for (int i = 0; i < 3; i++) {
			prices.add(null);
		}
		findViewById(R.id.iv_share).setVisibility(View.VISIBLE);
		findViewById(R.id.iv_store).setVisibility(View.VISIBLE);
		topTitle = findViewById(R.id.xd);
		mTitle = (TextView) findViewById(R.id.title_text);
		mTitle.setText(mProductName);

		findViewById(R.id.title_back).setOnClickListener(mOnClickListener);
		findViewById(R.id.iv_share).setOnClickListener(mOnClickListener);
		mCollect = (ImageView) findViewById(R.id.iv_store);
		mCollect.setOnClickListener(mOnClickListener);
		mPullToRefreshListView.setOnScrollListener(mOnScrollListener);

		mTopTabsViews[0] = (TextView) topTitle.findViewById(R.id.tab_price);
		mTopTabsViews[1] = (TextView) topTitle.findViewById(R.id.tab_introduce);
		mTopTabsViews[2] = (TextView) topTitle.findViewById(R.id.tab_comment);
		mTopTabsViews[0].setText("门票");

		for (View view : mTopTabsViews) {
			view.setOnClickListener(mOnClickListener);
		}
		sharePopupWindow = new SharePopupWindow(mContext, View.inflate(mContext, R.layout.popup1, null),
				getResources().getDisplayMetrics().widthPixels, LayoutParams.WRAP_CONTENT);
		initDatas();

	}

	@Override
	protected void initEvents() {
	}

	/**
	 * 初始化数据
	 */
	private void initDatas() {
		getFirstView(new IRequest<Boolean>() {

			@Override
			public void request(Boolean t) {
				getPriceView(new IRequest<Boolean>() {

					@Override
					public void request(Boolean t) {
						getIntroView(new IRequest<Boolean>() {

							@Override
							public void request(Boolean t) {
								getCommentView(new IRequest<Boolean>() {

									@Override
									public void request(Boolean t) {
										getSecondView();
										mPullToRefreshListView.setAdapter(mPriceAdapter);
										setTabSelected(0);
										mHandler.sendEmptyMessageDelayed(PARAM_TIMER, TIMER_DELAY);
										findViewById(R.id.loading).setVisibility(View.GONE);
									}
								});
							}
						});
					}
				});
			}
		});

		if (BaseApplication.getApplication().isLogin()) {
			HttpProtocol.isCollect(mProductId, BaseApplication.getApplication().getUser().getUserID(),
					PRODUCT_TYPE.TICKET.type, new IRequest<Boolean>() {

						@Override
						public void request(Boolean t) {
							if (t) {
								mCollect.setSelected(true);
							} else {
								mCollect.setSelected(false);
							}
						}
					});
		} else {
			mCollect.setSelected(false);
		}
	}

	private final OnScrollListener mOnScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			if (firstVisibleItem == 0) {
				topTitle.setVisibility(View.GONE);
			} else {
				topTitle.setVisibility(View.VISIBLE);
			}
		}
	};

	/**
	 * 获取评论的View
	 */
	private void getCommentView(final IRequest<Boolean> iRequest) {
		TicketHttpProtocol.getProductDetailToComment(mProductId, 0, PAGESIZE, new IRequest<List<TalkInfo>>() {

			@Override
			public void request(List<TalkInfo> t) {
				if (null != t) {
					t.add(0, null);
					t.add(0, null);
					mCommentAdapter = new CommentAdapter(mContext, t, PAGESIZE,
							R.layout.item_detail_comment_, R.layout.item_loading);
					iRequest.request(true);
				}
			}
		});
	}

	/**
	 * 获取介绍的View
	 */
	private View getIntroView(final IRequest<Boolean> iRequest) {
		if (null == mIntroView) {
			mIntroView = View.inflate(mContext, R.layout.item_intro_ticket, null);
			final TextView content = (TextView) mIntroView.findViewById(R.id.content);
			final TextView opentime = (TextView) mIntroView.findViewById(R.id.opentime);
			TicketHttpProtocol.getProductDetailToIntroduce(mProductId, new IRequest<TicketInfo>() {

				@Override
				public void request(TicketInfo t) {
					if (null != t) {
						mIntroAdapter = new IntroAdapter(mContext, prices, R.layout.item_price);
						if (!TextUtils.isEmpty(t.seneryLocation)) {
							content.setText(Html.fromHtml(t.seneryLocation));
							opentime.setText(t.seneryOpenTime);
						}
						if (null != iRequest) {
							iRequest.request(true);
						}
					}
				}
			});
		}
		return mIntroView;
	}

	/**
	 * 获取价格View
	 * @return
	 */
	private View getPriceView(final IRequest<Boolean> iRequest) {
		if (null == mPriceView) {
			mPriceView = View.inflate(mContext, R.layout.item_price, null);
			final LinearLayout container = (LinearLayout) mPriceView.findViewById(R.id.linear_price);
			final TextView content = (TextView) mPriceView.findViewById(R.id.intro);
			final View arrow = mPriceView.findViewById(R.id.arrow);
			TicketHttpProtocol.getProductDetailForPrice(mProductId, new IRequest<TicketPriceInfo>() {

				@Override
				public void request(final TicketPriceInfo t) {
					if (null != t) {
						if (!TextUtils.isEmpty(t.content)) {
							mShareContent = t.content;
						}
						if (!TextUtils.isEmpty(t.content)) {
							content.setText(t.content);
							if (t.content.length() > xdConfig.MAX_LENGTH) {
								arrow.setVisibility(View.VISIBLE);
							} else {
								arrow.setVisibility(View.GONE);
							}
						}

						arrow.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								if (showMore) {
									showMore = false;
									content.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
											xdConfig.MAX_LENGTH) });
									content.setText(t.content);
									arrow.setBackgroundResource(R.drawable.text_close);
								} else {
									content.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
											Integer.MAX_VALUE) });
									content.setText(t.content);
									arrow.setBackgroundResource(R.drawable.text_open);
									showMore = true;
								}
							}
						});

						mPriceAdapter = new PriceAdapter(mContext, prices, R.layout.item_price);
						if (null != t.ticketList) {
							for (final BargainPriceTicketInfo info : t.ticketList) {
								View view = View.inflate(mContext, R.layout.item_price_pay, null);
								TextView price = (TextView) view.findViewById(R.id.price);
								TextView title = (TextView) view.findViewById(R.id.title);
								price.setText(String.format("￥%s", info.vipPrice));
								title.setText(info.seneryTitle);
								view.findViewById(R.id.reserve).setOnClickListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
										if (!mApplication.isLogin()) {
											Intent intent1 = new Intent(mContext, LoginActivity.class);
											startActivity(intent1);
										} else {
											Intent intent = new Intent(TicketDetailActivity.this,
													ReservationActivity.class);
											intent.putExtra("type", ReservationActivity.TYPE_TICKET);
											intent.putExtra("price", info.vipPrice);
											intent.putExtra("title", info.seneryTitle);
											intent.putExtra("id", info.ticketId);
											startActivity(intent);
										}

									}
								});
								LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,
										LayoutParams.WRAP_CONTENT);
								lp.topMargin = 15;
								view.setLayoutParams(lp);
								container.addView(view);
							}
						}

						if (null != iRequest) {
							iRequest.request(true);
						}
					}
				}
			});
		}
		return mPriceView;
	}

	/**
	 * 获取item为0的view，此view是轮播图
	 * @return
	 */
	private View getFirstView(final IRequest<Boolean> iRequest) {
		if (null == firstView) {
			firstView = View.inflate(mContext, R.layout.detail_item_one, null);
			viewPager = (MyViewPager) firstView.findViewById(R.id.title_viewpager);
			final LinearLayout plan = (LinearLayout) firstView.findViewById(R.id.plan);
			TicketHttpProtocol.getProductDetailToPhotos(mProductId, new IRequest<List<String>>() {

				@Override
				public void request(List<String> t) {
					if (null != t) {
						mPhotosSize = t.size();
						// 初始化进度条
						mPlanViews = new View[t.size()];
						for (int i = 0; i < t.size(); i++) {
							View view = View.inflate(mContext, R.layout.item_plan, null);
							mPlanViews[i] = view;
							plan.addView(view);
						}
						if (t.size() > 0) {
							PhotosAdapter adapter = new PhotosAdapter(mContext, t);
							viewPager.setAdapter(adapter);
							viewPager.setOnPageChangeListener(mOnPageChangeListener);
						}
						setPagerSelected(0);
						if (null != iRequest) {
							iRequest.request(true);
						}
					} else {
						CommonUtil.showToast(mContext, "获取数据失败");
					}
				}
			});
		}
		return firstView;
	}

	private void setPagerSelected(int position) {
		for (int i = 0; i < mPlanViews.length; i++) {
			if (position == i) {
				mPlanViews[i].setSelected(true);
			} else {
				mPlanViews[i].setSelected(false);
			}
		}
	}

	private final OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int position) {
			setPagerSelected(position % mPhotosSize);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	};

	/**
	 * 此view为item为1的view，为tab切换的view
	 * @return
	 */
	private View getSecondView() {
		if (null == secondView) {
			secondView = View.inflate(mContext, R.layout.detail_item_2, null);

			mTabsViews[0] = (TextView) secondView.findViewById(R.id.tab_price);
			mTabsViews[1] = (TextView) secondView.findViewById(R.id.tab_introduce);
			mTabsViews[2] = (TextView) secondView.findViewById(R.id.tab_comment);
			mTabsViews[0].setText("门票");
			for (View view : mTabsViews) {
				view.setOnClickListener(mOnClickListener);
			}
		}
		return secondView;
	}

	private final OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tab_price:
				setTabSelected(0);
				mPullToRefreshListView.setAdapter(mPriceAdapter);
				break;
			case R.id.tab_introduce:
				setTabSelected(1);
				mPullToRefreshListView.setAdapter(mIntroAdapter);
				break;
			case R.id.tab_comment:
				setTabSelected(2);
				mPullToRefreshListView.setAdapter(mCommentAdapter);
				break;
			case R.id.title_back:
				finish();
				break;
			case R.id.iv_share:
				sharePopupWindow.setInfors(mController, mProductName, mShareContent, "");
				sharePopupWindow.showAtLocation(findViewById(R.id.top), Gravity.BOTTOM, 0, 0);
				break;
			case R.id.iv_store:// 收藏
				if (BaseApplication.getApplication().isLogin()) {
					collect();
				} else {
					CommonUtil.showToast(mContext, "尚未登录，请先登录!");
					Intent intent = new Intent(TicketDetailActivity.this, LoginActivity.class);
					startActivityForResult(intent, 100);
				}
				break;
			default:
				break;
			}
		}
	};

	private void collect() {
		mCollect.setEnabled(false);
		if (mCollect.isSelected()) {
			HttpProtocol.cancelCollect(mProductId, BaseApplication.getApplication().getUser().getUserID(),
					PRODUCT_TYPE.TICKET.type, new IRequest<Boolean>() {

						@Override
						public void request(Boolean t) {
							if (t) {
								mCollect.setSelected(false);
								CRToast.show(mContext, "取消收藏成功！");
							} else {
								CRToast.show(mContext, "取消收藏失败！");
							}
							mCollect.setEnabled(true);
						}
					});
		} else {
			HttpProtocol.addCollect(mProductId, BaseApplication.getApplication().getUser().getUserID(),
					PRODUCT_TYPE.TICKET.type, new IRequest<Boolean>() {

						@Override
						public void request(Boolean t) {
							if (t) {
								mCollect.setSelected(true);
								CRToast.show(mContext, "添加收藏成功！");
							} else {
								CRToast.show(mContext, "添加收藏失败！");
							}
							mCollect.setEnabled(true);
						}
					});
		}
	}

	private void setTabSelected(int index) {
		for (int i = 0; i < mTabsViews.length; i++) {
			if (i == index) {
				mTabsViews[i].setSelected(true);
				mTopTabsViews[i].setSelected(true);
			} else {
				mTabsViews[i].setSelected(false);
				mTopTabsViews[i].setSelected(false);
			}
		}
	}

	/**
	 * 评论的适配器
	 * @author Simba
	 *
	 */
	class CommentAdapter extends XinDaoBaseAdapter<TalkInfo> {

		public CommentAdapter(Context context, List<TalkInfo> iniData, int pageSize, int res, int loadingRes) {
			super(context, iniData, pageSize, res, loadingRes);
		}

		class ViewHolder {
			TextView name;
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent, TalkInfo t) {
			if (position == 0) {
				return getFirstView(null);
			} else if (position == 1) {
				return getSecondView();
			} else {
				View view = View.inflate(mContext, R.layout.item_detail_comment_, null);
				TextView name = (TextView) view.findViewById(R.id.title);
				TextView content = (TextView) view.findViewById(R.id.content);
				TextView time = (TextView) view.findViewById(R.id.time);
				name.setText(t.talkName);
				content.setText(t.talkContent);
				time.setText(CommonUtil.formatTime(t.talkTime * 1000, true));
				return view;
			}
		}

		@Override
		public boolean isEnabled(int position) {
			return false;
		}

		@Override
		public void nextPage(int start, int size, final ILoadNextPageData<TalkInfo> iLoadNextPageData) {
			TicketHttpProtocol.getProductDetailToComment(mProductId, start, size,
					new IRequest<List<TalkInfo>>() {

						@Override
						public void request(List<TalkInfo> t) {
							if (null != t) {
								iLoadNextPageData.loadNextPageData(t);
							}
						}
					});
		}

	}

	/**
	 * 介绍的适配器
	 * @author Simba
	 *
	 */
	class IntroAdapter extends MyBaseAdapter<String> {

		public IntroAdapter(Context context, List<String> mList, int resId) {
			super(context, mList, resId);
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent, String t) {
			if (position == 0) {
				return getFirstView(null);
			} else if (position == 1) {
				return getSecondView();
			} else {
				return getIntroView(null);
			}
		}

		@Override
		public boolean isEnabled(int position) {
			return false;
		}
	}

	/**
	 * 价格的适配器
	 * @author Simba
	 *
	 */
	class PriceAdapter extends MyBaseAdapter<String> {

		public PriceAdapter(Context context, List<String> mList, int resId) {
			super(context, mList, resId);
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent, String t) {
			if (position == 0) {
				return getFirstView(null);
			} else if (position == 1) {
				return getSecondView();
			} else {
				return getPriceView(null);
			}
		}

		@Override
		public boolean isEnabled(int position) {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 100) {
			HttpProtocol.cancelCollect(mProductId, BaseApplication.getApplication().getUser().getUserID(),
					PRODUCT_TYPE.TICKET.type, new IRequest<Boolean>() {
						@Override
						public void request(Boolean t) {
							if (t) {
								mCollect.setSelected(false);
							}
							mCollect.setEnabled(true);
						}
					});
		}

		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (sharePopupWindow.isShowing()) {
			sharePopupWindow.dismiss();
			return false;
		} else
			return super.onKeyDown(keyCode, event);
	}
}
